package com.szh.gulimall.product.service.impl;

import com.szh.gulimall.product.service.CategoryBrandRelationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szh.common.utils.PageUtils;
import com.szh.common.utils.Query;
import com.szh.gulimall.product.dao.BrandDao;
import com.szh.gulimall.product.entity.BrandEntity;
import com.szh.gulimall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    private static final Logger LOGGER = LoggerFactory.getLogger(BrandServiceImpl.class);

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.eq("brand_id", key).or().like("name", key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                queryWrapper
        );
        LOGGER.info("list ===> {}", page.getRecords());
        LOGGER.info("totalCount ===> {}", page.getTotal());
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void updateDetail(BrandEntity brand) {
        //首先更新品牌表自己的数据
        this.updateById(brand);
        if (!StringUtils.isEmpty(brand.getName())) {
            //然后同步更新分类-品牌关联表中的数据
            categoryBrandRelationService.updateBrandInfo(brand.getBrandId(), brand.getName());
            //TODO 更新其他关联表的数据
        }
    }

    /**
     * 根据id集合批量查询品牌信息
     * 为search检索服务提供的远程接口，考虑到远程调用可能会比较耗时，所以将返回结果放入Redis缓存中
     */
    @Cacheable(cacheNames = {"brand"}, key = "#root.methodName")
    @Override
    public List<BrandEntity> listByBrandIds(List<Long> brandIds) {
        QueryWrapper<BrandEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("brand_id", brandIds);
        return this.list(queryWrapper);
    }

}